document.addEventListener('DOMContentLoaded', function() {
    // 获取所有滑块元素
    const temperatureSlider = document.getElementById('temperature-slider');
    const humiditySlider = document.getElementById('humidity-slider');
    const waterLevelSlider = document.getElementById('water-level-slider');

    // 获取显示值的元素
    const temperatureValue = document.getElementById('temperature-value');
    const humidityValue = document.getElementById('humidity-value');
    const waterLevelValue = document.getElementById('water-level-value');

    // 获取传感器显示元素
    const temperatureMercury = document.getElementById('temperature-mercury');
    const humidityBar = document.getElementById('humidity-bar');
    const humidityDots = document.getElementById('humidity-dots');
    const waterLevel = document.getElementById('water-level');

    // 创建图表
    const chartConfig = {
        type: 'line',
        options: {
            responsive: true,
            maintainAspectRatio: false,
            animation: {
                duration: 0
            },
            scales: {
                x: {
                    type: 'time',
                    time: {
                        unit: 'second',
                        displayFormats: {
                            second: 'HH:mm:ss'
                        },
                        tooltipFormat: 'HH:mm:ss'
                    },
                    title: {
                        display: true,
                        text: '时间'
                    },
                    ticks: {
                        maxRotation: 0
                    }
                },
                y: {
                    min: 0,
                    max: 100,
                    title: {
                        display: true,
                        text: '数值'
                    }
                }
            },
            plugins: {
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${context.dataset.label}: ${context.parsed.y}`;
                        }
                    }
                }
            }
        }
    };

    // 温度图表
    const temperatureChart = new Chart(
        document.getElementById('temperature-chart'),
        {
            ...chartConfig,
            options: {
                ...chartConfig.options,
                scales: {
                    ...chartConfig.options.scales,
                    y: {
                        ...chartConfig.options.scales.y,
                        max: 40
                    }
                }
            },
            data: {
                labels: [],
                datasets: [{
                    label: '温度 (°C)',
                    data: [],
                    borderColor: 'rgb(255, 99, 132)',
                    tension: 0.1,
                    fill: false
                }]
            }
        }
    );

    // 湿度图表
    const humidityChart = new Chart(
        document.getElementById('humidity-chart'),
        {
            ...chartConfig,
            data: {
                labels: [],
                datasets: [{
                    label: '湿度 (%)',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1,
                    fill: false
                }]
            }
        }
    );

    // 水位图表
    const waterLevelChart = new Chart(
        document.getElementById('water-level-chart'),
        {
            ...chartConfig,
            data: {
                labels: [],
                datasets: [{
                    label: '水位 (%)',
                    data: [],
                    borderColor: 'rgb(54, 162, 235)',
                    tension: 0.1,
                    fill: false
                }]
            }
        }
    );

    // 更新图表数据
    function updateCharts(data) {
        const timestamps = data.timestamps.map(t => new Date(t));
        const now = new Date();
        
        // 如果没有数据，使用当前时间
        if (timestamps.length === 0) {
            timestamps.push(now);
            data.temperature.push(null);
            data.humidity.push(null);
            data.water_level.push(null);
        }
        
        // 更新最后一个时间点为当前时间
        timestamps[timestamps.length - 1] = now;
        
        temperatureChart.data.labels = timestamps;
        temperatureChart.data.datasets[0].data = data.temperature.map((value, index) => ({
            x: timestamps[index],
            y: value
        }));
        temperatureChart.update();

        humidityChart.data.labels = timestamps;
        humidityChart.data.datasets[0].data = data.humidity.map((value, index) => ({
            x: timestamps[index],
            y: value
        }));
        humidityChart.update();

        waterLevelChart.data.labels = timestamps;
        waterLevelChart.data.datasets[0].data = data.water_level.map((value, index) => ({
            x: timestamps[index],
            y: value
        }));
        waterLevelChart.update();
    }

    // 从后端获取历史数据
    function fetchHistoryData() {
        fetch('/api/history-data')
            .then(response => response.json())
            .then(data => {
                updateCharts(data);
            })
            .catch(error => console.error('Error fetching history data:', error));
    }

    // 定时更新图表
    setInterval(fetchHistoryData, 1000);
    
    // 初始加载数据
    fetchHistoryData();

    // 聊天功能
    const chatBox = document.getElementById('chat-box');
    const chatInput = document.getElementById('chat-input');
    const sendButton = document.getElementById('send-message');

    // 添加消息到聊天框
    function addMessage(content, isUser = true) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${isUser ? 'user' : 'assistant'}`;
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        messageContent.textContent = content;
        
        const messageTime = document.createElement('div');
        messageTime.className = 'message-time';
        messageTime.textContent = new Date().toLocaleTimeString();
        
        messageDiv.appendChild(messageContent);
        messageDiv.appendChild(messageTime);
        
        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    // 发送消息
    async function sendMessage() {
        const message = chatInput.value.trim();
        if (!message) return;

        addMessage(message, true);
        chatInput.value = '';

        try {
            const response = await fetch('/api/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message })
            });

            const data = await response.json();
            addMessage(data.response, false);
        } catch (error) {
            console.error('Error sending message:', error);
            addMessage('抱歉，发生了一些错误，请稍后再试。', false);
        }
    }

    // 绑定发送按钮点击事件
    sendButton.addEventListener('click', sendMessage);

    // 绑定输入框回车事件
    chatInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // 更新温度计
    function updateTemperature(value) {
        const height = (value / 40) * 100;
        temperatureMercury.style.height = `${height}%`;
        temperatureValue.textContent = `${value}°C`;
        throttledUpdateSensorData('temperature', value);
    }

    // 更新湿度显示 (New Version)
    function updateHumidity(value) {
        if (humidityBar && humidityValue && humidityDots) {
            humidityBar.style.width = `${value}%`;
            humidityValue.textContent = `${value}%`;
            
            const dots = humidityDots.querySelectorAll('.humidity-dot');
            const activeCount = Math.floor((value / 100) * dots.length);
            
            dots.forEach((dot, index) => {
                if (index < activeCount) {
                    dot.style.background = 'rgba(255, 255, 255, 0.8)';
                } else {
                    dot.style.background = 'rgba(255, 255, 255, 0.2)';
                }
            });
            throttledUpdateSensorData('humidity', value);
        }
    }
    
    // 创建湿度数据点 (New Function)
    function createHumidityDots() {
        if (!humidityDots) return;
        humidityDots.innerHTML = '';
        const dotCount = 20; 
        for (let i = 0; i < dotCount; i++) {
            const dot = document.createElement('div');
            dot.className = 'humidity-dot';
            humidityDots.appendChild(dot);
        }
    }

    // 更新水位
    function updateWaterLevel(value) {
        if (waterLevel && waterLevelValue) {
            waterLevel.style.height = `${value}%`;
            waterLevelValue.textContent = `${value}%`;
            throttledUpdateSensorData('water_level', value);
        }
    }

    // 更新传感器数据到后端 (Throttled)
    const throttledUpdateSensorData = throttle(updateSensorData, 500); // Throttle updates to every 500ms
    function updateSensorData(type, value) {
        // console.log(`Updating ${type} to ${value}`); // Debug log - Using original endpoint and format
        fetch(`/api/update-sensor`, { // CORRECTED ENDPOINT
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ // CORRECTED BODY FORMAT
                type: type,
                value: parseFloat(value)
            })
        })
        .then(response => response.json())
        .then(data => {
            // Assuming the original response format might be different, adjust logging if needed
            if (data.status !== 'success') { 
                console.error(`Error updating ${type} sensor data via /api/update-sensor:`, data.message || data);
            } else {
                console.log(`Sensor ${type} updated successfully via /api/update-sensor`);
            }
        })
        .catch(error => console.error(`Fetch error updating ${type} sensor data via /api/update-sensor:`, error));
    }

    // 节流函数
    function throttle(func, limit) {
        let lastFunc;
        let lastRan;
        return function(...args) {
            const context = this;
            if (!lastRan) {
                func.apply(context, args);
                lastRan = Date.now();
            } else {
                clearTimeout(lastFunc);
                lastFunc = setTimeout(function() {
                    if ((Date.now() - lastRan) >= limit) {
                        func.apply(context, args);
                        lastRan = Date.now();
                    }
                }, limit - (Date.now() - lastRan));
            }
        }
    }

    // 初始化传感器
    function initializeSensors() {
        if (temperatureSlider) {
            const initialTemp = parseInt(temperatureSlider.value);
            updateTemperature(initialTemp);
            temperatureSlider.addEventListener('input', (e) => updateTemperature(parseInt(e.target.value)));
        }
        
        if (humiditySlider) {
            createHumidityDots(); // Create dots first
            const initialHumidity = parseInt(humiditySlider.value);
            updateHumidity(initialHumidity);
            humiditySlider.addEventListener('input', (e) => updateHumidity(parseInt(e.target.value)));
        }
        
        if (waterLevelSlider) {
            const initialWater = parseInt(waterLevelSlider.value);
            updateWaterLevel(initialWater);
            waterLevelSlider.addEventListener('input', (e) => updateWaterLevel(parseInt(e.target.value)));
        }
        
        // 初始加载历史数据
        fetchHistoryData();
        // 设置定时获取历史数据
        setInterval(fetchHistoryData, 5000); // Update charts every 5 seconds based on history
    }

    // Initialize everything
    initializeSensors();
    // fetchDeviceStatus(); // Assuming this is called elsewhere or needed
});



// 获取设备状态元素
const acStatus = document.getElementById('ac-status');
const dehumidifierStatus = document.getElementById('dehumidifier-status');
const valveStatus = document.getElementById('valve-status');

// 更新设备状态显示
function updateDeviceStatus(data) {
    // 更新空调状态
    const acIndicator = acStatus.querySelector('.status-indicator');
    const acStatusText = acStatus.querySelector('.status-text');
    document.getElementById('ac-temperature').textContent = `${data.ac.temperature}°C`;
    document.getElementById('ac-mode').textContent = data.ac.mode;
    if (data.ac.running) {
        acIndicator.classList.remove('off');
        acIndicator.classList.add('on');
        acStatusText.textContent = '运行中';
    } else {
        acIndicator.classList.remove('on');
        acIndicator.classList.add('off');
        acStatusText.textContent = '关闭';
    }

    // 更新除湿器状态
    const dehumidifierIndicator = dehumidifierStatus.querySelector('.status-indicator');
    const dehumidifierStatusText = dehumidifierStatus.querySelector('.status-text');
    document.getElementById('dehumidifier-target').textContent = `${data.dehumidifier.target}%`;
    document.getElementById('dehumidifier-mode').textContent = data.dehumidifier.mode;
    if (data.dehumidifier.running) {
        dehumidifierIndicator.classList.remove('off');
        dehumidifierIndicator.classList.add('on');
        dehumidifierStatusText.textContent = '运行中';
    } else {
        dehumidifierIndicator.classList.remove('on');
        dehumidifierIndicator.classList.add('off');
        dehumidifierStatusText.textContent = '关闭';
    }

    // 更新水阀状态
    const valveIndicator = valveStatus.querySelector('.status-indicator');
    const valveStatusText = valveStatus.querySelector('.status-text');
    document.getElementById('valve-opening').textContent = `${data.valve.opening}%`;
    document.getElementById('valve-flow').textContent = `${data.valve.flow} L/min`;
    if (data.valve.running) {
        valveIndicator.classList.remove('off');
        valveIndicator.classList.add('on');
        valveStatusText.textContent = '开启';
    } else {
        valveIndicator.classList.remove('on');
        valveIndicator.classList.add('off');
        valveStatusText.textContent = '关闭';
    }
}

// 获取设备状态
function fetchDeviceStatus() {
    fetch('/api/device-status')
        .then(response => response.json())
        .then(data => {
            updateDeviceStatus(data);
        })
        .catch(error => console.error('Error fetching device status:', error));
}

// 定时更新设备状态
setInterval(fetchDeviceStatus, 1000);

// 初始化设备状态
fetchDeviceStatus();


